<template>
  <div class="page">
    <el-row type="flex" justify="center" :align="'middle'" class="container">
      <el-col :lg="14" :xl="10" class="hidden-md-and-down">
        <el-row class="panel">
          <el-col :span="12">
            <div class="left">
              <img src="../../assets/login/logo.png" class="logo" alt=""/>
              <img src="../../assets/login/big-1.png" class="big" alt=""/>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="right">
              <div class="title-container">
                <h2>企业在线办公系统</h2>
                <!--                <span>( Ver 1.0 )</span>-->
              </div>
              <div v-if="!qrCodeVisible">
                <div class="row">
                  <el-input
                      v-model="username"
                      placeholder="用户名"
                      prefix-icon="el-icon-user"
                      clearable="clearable"
                  />
                </div>
                <div class="row">
                  <el-input
                      type="password"
                      v-model="password"
                      placeholder="密码"
                      prefix-icon="el-icon-lock"
                      clearable="clearable"
                  />
                </div>
                <div class="row">
                  <el-button type="primary" class="btn" @click="login">登陆系统</el-button>
                </div>
                <div class="row"><a class="link" @click="showForgetPassword">忘记密码</a></div>
              </div>
            </div>
          </el-col>
        </el-row>
      </el-col>
    </el-row>

    <el-dialog class="forget-dialog" title="忘记密码" v-model="showDialog">
      <el-form
          ref="forgetForm"
          :model="forgetForm"
          :rules="forgetRules"
          class="forget-form"
          autocomplete="on"
          label-position="left"
      >

        <div>
          <h3
              style="font-size: 26px;
              color: #2691FF;
              margin: 0 auto 10px auto;
              text-align: center;
              font-weight: bold;">
            忘记密码
          </h3>
        </div>

        <el-form-item prop="account">
          <el-input
              ref="account"
              prefix-icon="el-icon-user"
              v-model="forgetForm.account"
              placeholder="请输入您的邮箱账号"
              name="account"
              type="text"
              tabindex="1"
              autocomplete="on"
          />
        </el-form-item>

        <el-tooltip v-model="capsTooltip" content="Caps lock is On" placement="right" manual>
          <el-form-item prop="password">
            <el-input
                :key="passwordType"
                ref="password"
                v-model="forgetForm.password"
                :type="passwordType"
                placeholder="请输入您新的密码"
                name="password"
                prefix-icon="el-icon-lock"
                tabindex="2"
                autocomplete="on"
                @keyup.native="checkCapslock"
                @blur="capsTooltip = false"
                @keyup.enter.native="handleConfirm"
            />
            <span class="show-pwd" @click="showPwd">
              <i :class="passwordType === 'password' ? 'eye' : 'eye-open'"/>
            </span>
          </el-form-item>
        </el-tooltip>

        <el-tooltip v-model="capsTooltip" content="Caps lock is On" placement="right" manual>
          <el-form-item prop="confirmPassword">
            <el-input
                :key="passwordType"
                ref="password"
                v-model="forgetForm.confirmPassword"
                :type="passwordType"
                placeholder="请再次输入您的密码"
                name="confirmPassword"
                prefix-icon="el-icon-lock"
                tabindex="2"
                autocomplete="on"
                @keyup.native="checkCapslock"
                @blur="capsTooltip = false"
                @keyup.enter.native="handleConfirm"
            />
            <span class="show-pwd" @click="showPwd">
              <i :class="passwordType === 'password' ? 'eye' : 'eye-open'"/>
            </span>
          </el-form-item>
        </el-tooltip>

        <el-form-item prop="verify" style="width: 65%;float: left;">
          <el-input
              ref="username"
              prefix-icon="el-icon-s-comment"
              v-model="forgetForm.verify"
              placeholder="请输入您收到的验证码"
              name="username"
              type="text"
              tabindex="1"
              autocomplete="on"
          />
        </el-form-item>
        <el-button
            id="get-verify-btn"
            style="color: #2691FF;width: 35%;height: 40px;background: transparent"
            @click="sendVerify"
        >
          发送验证码
        </el-button>

        <div style="position:relative">
          <el-button
              :loading="loading"
              type="primary"
              style="width: 100%;margin-bottom: 25px;"
              @click.native.prevent="handleConfirm"
          >
            确认
          </el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import 'element-plus/lib/theme-chalk/display.css';
import {isPassword, isEmail} from "../../utils/validate";
import router from '../../router';

export default {
  data: function () {
    let validateForgetUsername = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入你的邮箱账户'))
      } else {
        if (!isEmail(value)) {
          callback(new Error('邮箱格式不正确，请重新输入'))
        } else {
          callback()
        }
      }
    };
    let validatePassword1 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入新的密码'))
      } else {
        if (this.forgetForm.confirmPassword !== '') {
          this.$refs.forgetForm.validateField('confirmPassword')
        }
        callback()
      }
    };
    let validatePassword2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入新的密码'))
      } else if (value !== this.forgetForm.password) {
        callback(new Error('两次输入的密码不一致，请重新输入'))
      } else {
        callback()
      }
    }
    return {
      username: null,
      password: null,
      qrCodeVisible: false,
      qrCode: '',
      uuid: null,
      qrCodeTimer: null,
      loginTimer: null,
      user: {
        username: null,
        userId: null
      },
      passwordType: 'password',
      capsTooltip: false,
      loading: false,
      showDialog: false,
      redirect: undefined,
      forgetForm: {
        account: '',
        password: '',
        confirmPassword: '',
        verify: ''
      },
      forgetRules: {
        account: [{required: true, trigger: 'blur', validator: validateForgetUsername}],
        password: [{required: true, trigger: 'blur', validator: validatePassword1}],
        confirmPassword: [{required: true, trigger: 'blur', validator: validatePassword2}],
        verify: [{required: true, message: '您的验证码不能为空'}]
      },
    };
  },
  methods: {
    showForgetPassword() {
      this.showDialog = true
    },
    checkCapslock(e) {
      const {key} = e
      this.capsTooltip = key && key.length === 1 && (key >= 'A' && key <= 'Z')
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    // 获取验证码
    sendVerify() {
      if (isEmail(this.forgetForm.account)) {
        let that = this
        let data = {email: this.forgetForm.account}
        // 发送请求获取验证码，发送成功给出提出
        this.$http("user/sendVerify", "POST", data, false, function (response) {
          const data = response.rows
          if (data === 1) {
            // this.$message.success('The verification code has been sent successfully, please check your email!')
            that.$message({
              type: 'success',
              message: '验证码发送成功，请查收您的邮箱',
              duration: 1000
            })
            let nums = 60
            const verify = document.getElementById('get-verify-btn')
            verify.disabled = 'disabled'
            verify.innerText = nums + '秒后重新获取'
            // 一秒执行一次
            // eslint-disable-next-line prefer-const
            let clock = setInterval(() => {
              nums--
              if (nums > 0) {
                verify.innerText = nums + '秒后重新获取'
              } else {
                // 清除 js 定时器
                clearInterval(clock)
                verify.disabled = false
                verify.innerText = '获取验证码'
                // 重置时间
                nums = 60
              }
            }, 1000)
          } else {
            that.$message({
              message: '发送失败，请确认您的输入是否有误!',
              type: 'error',
              duration: 3000
            })
          }
        })
      } else {
        this.$message({
          message: '请输入您的邮箱账号!',
          type: 'error',
          duration: 3000
        })
      }
    },
    handleConfirm() {
      let that = this
      this.$refs.forgetForm.validate(valid => {
        if (valid) {
          let data = {
            account: this.forgetForm.account, password: this.forgetForm.password,
            confirmPassword: this.forgetForm.confirmPassword, verify: this.forgetForm.verify
          }
          let that = this
          this.$http("user/resetPassword", "POST", data, true, function (response) {
            const data = response.rows
            if (data >= 1) {
              that.$message({
                message: '密码修改成功，请重新返回登录!',
                type: 'success',
                duration: 3000
              })
              that.username = that.forgetForm.account
              that.password = that.forgetForm.password
              that.showDialog = false
            }
          })
        } else {
          that.$message({
            message: '修改失败！请确认您的输入或稍后再试',
            type: 'error',
            duration: 3000
          })
          return false
        }
      })
    },
    login() {
      let _this = this;
      // 验证用户名
      if (!isPassword(this.password)) { // 验证密码
        this.$message({
          message: "密码格式不正确",
          type: "error",
          duration: 1200
        })
      } else {
        let data = {username: this.username, password: this.password};
        this.$http("user/login", "POST", data, true, function (response) {
          if (response.code === 200 && response.result) {
            //在浏览器的storage中存储用户权限列表，这样其他页面也可使用storage中的数据，实现共享
            let permissions = response.permissions;
            //取出Token令牌，保存到storage中
            let token = response.token;
            let user = response.user;
            localStorage.setItem("permissions", permissions);
            localStorage.setItem('token', token);
            localStorage.setItem('user', JSON.stringify(user));
            router.push({
              name: "Home"
            })
          } else {
            _this.$message({
              message: "登陆失败",
              type: "error",
              duration: 1200
            })
          }
        })
      }
    }
  }
};
</script>

<style lang="less" scoped="scoped">
@import url('../../style/login.less');

.forget-form {
  position: relative;
  width: 420px;
  max-width: 100%;
  //padding: 10px 35px 0;
  margin: 0 auto;
  overflow: hidden;
}

.forget-dialog {
  position: relative;
  width: 500px;
  height: 500px;
}
</style>
